package com.unibeta.cloudtest.mesher.auth.util;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.context.annotation.Configuration;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.unibeta.cloudtest.mesher.util.Log;

@Configuration
public class OAuthUtils {

//	@Value(value = "${oauth2.server.endpoint}")
//	static String authServerEndpoint;
//	@Value(value = "${oauth2.server.secret-key}")
//	static String secretKey;
//	@Value(value = "${oauth2.server.iv-parameter}")
//	static String ivParameter;
//	@Value(value = "${oauth2.client.clientId}")
//	static String clientId;
//	@Value(value = "${oauth2.client.clientSecret}")
//	static String clientSecret;

	/**
	 * 
	 * 
	 * @param clientId
	 * @param clientSecret
	 * @return
	 * 
	 *         <pre>
	  {
	    "access_token": "7caf4aac-3fc0-4898-9cf2-90ee855f2619",
	    "token_type": "bearer",
	    "refresh_token": "2c5baf98-fd81-4941-91c2-3265925ac6c5",
	    "expires_in": 41339,
	    "scope": "server",
	    "license": "made by insuredx-oauth",
	    "active": true,
	    "user_info": {
	        "password": null,
	        "username": "admin"
	     }
	   }
	 *         </pre>
	 */
	public static String authorize(String authServerEndpoint,String secretKey, String ivParameter, String clientId, String clientSecret,
			String username, String password, String scope) {

		Unirest.setTimeouts(0, 0);

		HttpResponse<String> response = null;
		try {
			byte[] basicAuthCode = Base64.getEncoder().encode((clientId + ":" + clientSecret).getBytes());

			response = Unirest.post(authServerEndpoint + "?grant_type=password")
					.header("Authorization", "Basic " + new String(basicAuthCode))
					.header("Accept-Language", " zh-CN,zh;").header("Content-Type", "application/x-www-form-urlencoded")
					.field("username", username).field("password", encrypt(password, secretKey, ivParameter))
					.field("scope", scope).asString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return response.getBody();
	}

	public static String encrypt(String data, String key, String ivStr) {
		String ivString = ivStr;
		// 偏移量
		byte[] iv = ivString.getBytes();
		try {
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			int blockSize = cipher.getBlockSize();
			byte[] dataBytes = data.getBytes();
			int length = dataBytes.length;
			// 计算需填充长度
			if (length % blockSize != 0) {
				length = length + (blockSize - (length % blockSize));
			}
			byte[] plaintext = new byte[length];
			// 填充
			System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
			SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
			// 设置偏移量参数
			IvParameterSpec ivSpec = new IvParameterSpec(iv);
			cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
			byte[] encryped = cipher.doFinal(plaintext);

			return Base64.getEncoder().encodeToString(encryped);

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// 解密
	public static String decrypt(String data, String key, String ivStr) {

		String ivString = ivStr;
		byte[] iv = ivString.getBytes();

		try {
			byte[] encryp = Base64.getEncoder().encode(data.getBytes());
			Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
			SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
			IvParameterSpec ivSpec = new IvParameterSpec(iv);
			cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
			byte[] original = cipher.doFinal(encryp);
			return new String(original);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		// Map m = OAuthUtils.authorize("test", "test", "admin",
		// "rKu1/348LvKp0rsVC06eCA==", "server");
		byte[] basicAuthCode = Base64.getEncoder().encode(("test:test").getBytes());

		String authServerEndpoint = "http://localhost:9999/auth/oauth/token";
		String secretKey = "pigxpigxpigxpigx";
		String ivParameter = secretKey;

		try {
			Log.println(authorize(authServerEndpoint,secretKey, secretKey, "test", "test", "jordan.xue", "Ebaotech1234", "server1"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
